//
//  BDTransactionRecordsViewController.m
//  BadBoy
//
//  Created by wen on 2017/9/7.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDTransactionRecordsViewController.h"
#import "BDGeneralCell.h"
#import "BDUserModel.h"
#import "BDShopDatePickerView.h"

@interface BDTransactionRecordsViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableDictionary *imageDic;
    NSDate *nowDate;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<BDTransactionRecordsModel *> *datasource;

@end

@implementation BDTransactionRecordsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"交易记录");
    _datasource = [NSMutableArray array];
    imageDic = [NSMutableDictionary dictionary];
    nowDate = [NSDate date];
    [self requestDatasource];
}

- (void)requestDatasource {
    [MBManager showLoadingAlert:@"" clickHidden:NO clickBlock:nil];
    BDUserModel *user = [BDUserModel getCurrentUser];
    NSString *url = [NSString stringWithFormat:@"%@balances/%@?type=1&page=%@&size=%@&start_at=0&end_at=%@", KBDBaseURL, @(user.user_id), self.startPage, self.pageSize, @((long)[nowDate timeIntervalSince1970])];
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
        
        NSMutableArray *imageArray = [NSMutableArray array];
        for (NSDictionary *subDic in x[@"list"]) {
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:[subDic[@"created_at"] integerValue]];
            BDTransactionRecordsModel *recordModel = nil;
            for (BDTransactionRecordsModel *ob in _datasource) {
                if (ob.year == date.year && ob.month == date.month) {
                    recordModel = ob;
                    break;
                }
            }
            if (recordModel == nil) {
                recordModel = [[BDTransactionRecordsModel alloc] init];
                recordModel.recordsArray = [NSMutableArray array];
                recordModel.year = date.year;
                recordModel.month = date.month;
                recordModel.revenue = [NSDecimalNumber decimalNumberWithString:@"0"];
                recordModel.spending = [NSDecimalNumber decimalNumberWithString:@"0"];
                [self.datasource addObject:recordModel];
                for (NSDictionary *outDic in x[@"outlay"]) {
                    NSString *dateString = outDic[@"date"];
                    NSArray *arr = [dateString componentsSeparatedByString:@"-"];
                    NSInteger year = [arr.firstObject integerValue];
                    NSInteger month = [arr.lastObject integerValue];
                    if (year == recordModel.year && month == recordModel.month) {
                        recordModel.spending = [NSDecimalNumber decimalNumberWithString:outDic[@"balance"]];
                        break;
                    }
                }
                for (NSDictionary *inDic in x[@"income"]) {
                    NSString *dateString = inDic[@"date"];
                    NSArray *arr = [dateString componentsSeparatedByString:@"-"];
                    NSInteger year = [arr.firstObject integerValue];
                    NSInteger month = [arr.lastObject integerValue];
                    if (year == recordModel.year && month == recordModel.month) {
                        recordModel.revenue = [NSDecimalNumber decimalNumberWithString:inDic[@"balance"]];
                        break;
                    }
                }
            }
            
            NSString *dateString = [NSString stringWithFormat:ASLocalizedString(@"%zd月%zd日 %zd:%zd"), date.month, date.day, date.hour, date.minute];
            BDGeneralModel *gengeralModel = [[BDGeneralModel alloc] init].modeEqual(BDGeneralCellModeLabel).imageTypeEqual(BDGeneralCellImageTypeURL).imageEqual(subDic[@"logo"]).titleEqual(subDic[@"title"]).laberStringEqual(subDic[@"balance"]).subTitleEqual(dateString).extensionEqual(date);
            [recordModel.recordsArray addObject:gengeralModel];
            if (![imageArray containsObject:gengeralModel.image]) {
                [imageArray addObject:gengeralModel.image];
            }
        }
        
        for (int i =0; i < imageArray.count; i++) {
            NSURL *url = [NSURL URLWithString:imageArray[i]];
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *image = [[UIImage alloc] initWithData:data];
            [[SDWebImageManager sharedManager] saveImageToCache:image forURL:url];
        }
        
        for (BDTransactionRecordsModel *recordsModel in _datasource) {
            [recordsModel.recordsArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                NSDate *date1 = ((BDGeneralModel *)obj1).extension;
                NSDate *date2 = ((BDGeneralModel *)obj2).extension;
                return date1.timeIntervalSince1970 < date2.timeIntervalSince1970;
            }];
        }
        
        [self.datasource sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            BDTransactionRecordsModel *a = obj1;
            BDTransactionRecordsModel *b = obj2;
            return (a.year * 12 + a.month) < (b.year * 12 + b.month);
        }];
        [MBManager hideAlert];
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:_datasource.count];
        [self.tableView reloadData];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [MBManager hideAlert];
        [self showErrorViewWithTapBlock:^{
            
        }];
        // BDLog(ASLocalizedString(@"请求错误"));
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource[section].recordsArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDGeneralModel *generalModel = self.datasource[indexPath.section].recordsArray[indexPath.row];
    BDGeneralCell *cell = [BDGeneralCell cellForTableView:tableView model:generalModel indexPath:indexPath identifier:@"recordsCell"];
    cell.subviewBlock = ^(BDGeneralCell *generalCell) {
        generalCell.imageView.size = CGSizeMake(44, 44);
        generalCell.imageView.left = 15;
        generalCell.imageView.centerY = generalCell.height / 2.0;
        
        generalCell.textLabel.font = [UIFont systemFontOfSize:16];
        generalCell.textLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
        [generalCell.textLabel sizeToFit];
        generalCell.textLabel.top = generalCell.imageView.top + 2.5;
        generalCell.textLabel.left = generalCell.imageView.right + 15;
        
        generalCell.detailTextLabel.font = [UIFont systemFontOfSize:13];
        generalCell.detailTextLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [generalCell.detailTextLabel sizeToFit];
        generalCell.detailTextLabel.bottom = generalCell.imageView.bottom - 2.5;
        generalCell.detailTextLabel.left = generalCell.textLabel.left;
        
        generalCell.aLabel.font = [UIFont systemFontOfSize:18];
        generalCell.aLabel.textColor = generalModel.subTitle.floatValue > 0 ? [UIColor colorWithHexString:@"ff992b"] : [UIColor colorWithHexString:@"1c1c1c"];
        [generalCell.aLabel sizeToFit];
        generalCell.aLabel.right = generalCell.width - 15;
        generalCell.aLabel.centerY = generalCell.height / 2.0;
    };
    
    return cell;
}

-(CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 84;
}

-(CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 62;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BDTransactionRecordsModel *recordModel = self.datasource[section];
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 62)];
    headView.backgroundColor = [UIColor colorWithHexString:@"f2f2f2"];
    
    UILabel *dateLabel = [[UILabel alloc] init];
    dateLabel.font = [UIFont systemFontOfSize:13];
    dateLabel.text = [NSString stringWithFormat:ASLocalizedString(@"%zd年%zd月"), recordModel.year, recordModel.month];
    [dateLabel sizeToFit];
    dateLabel.textColor = [UIColor colorWithHexString:@"1c1c1c"];
    dateLabel.top = 15;
    dateLabel.left = 15;
    [headView addSubview:dateLabel];
    
    UILabel *runningWaterLabel = [[UILabel alloc] init];
    runningWaterLabel.font = [UIFont systemFontOfSize:13];
    runningWaterLabel.text = [NSString stringWithFormat:ASLocalizedString(@"支出 ¥%@ 收入 ¥%@"), recordModel.spending, recordModel.revenue];
    [runningWaterLabel sizeToFit];
    runningWaterLabel.textColor = [UIColor colorWithHexString:@"767676"];
    runningWaterLabel.top = dateLabel.bottom + 8;
    runningWaterLabel.left = 15;
    [headView addSubview:runningWaterLabel];
    
    UIButton *dateButton = [UIButton buttonWithType:UIButtonTypeCustom];
    dateButton.size = CGSizeMake(22, 22);
    dateButton.right = kBDScreenWidth - 15;
    dateButton.top = 20;
    [dateButton setBackgroundImage:[UIImage imageNamed:@"icon_rili"] forState:UIControlStateNormal];
    [dateButton setEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
    [headView addSubview:dateButton];
    
    [[dateButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        BDShopDatePickerView *datePick = [BDShopDatePickerView datePick];
        [datePick showWithYear:recordModel.year month:recordModel.month finishBlock:^(NSInteger aYear, NSInteger aMonth) {
            if (recordModel.year == aYear && recordModel.month == aMonth) {
                return;
            }
            nowDate = [NSDate dateWithString:[NSString stringWithFormat:@"%04zd-%02zd", aYear, aMonth] format:@"yyyy-MM"];
            [_datasource removeAllObjects];
            [self requestDatasource];
        }];
    }];
    
    return headView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
